package com.lagou.edu.controller;

import com.lagou.edu.dao.LagouTokenDao;
import com.lagou.edu.pojo.LagouToken;
import com.lagou.edu.service.SignAndRegisterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("user")
public class SignAndRegisterController {

    @Autowired
    private SignAndRegisterService signAndRegisterService;

    /**
     * 判断邮箱是否已经注册
     *
     * @param email
     * @return
     */
    @GetMapping("/isRegistered/{email}")
    public Boolean isRegisted(@PathVariable("email") String email) {
        return signAndRegisterService.isRegistered(email);
    }

    @GetMapping("/register/{email}/{password}/{code}")
    public Integer register(@PathVariable("email") String email, @PathVariable("password") String password, @PathVariable("code") String code) {
        return signAndRegisterService.register(email, password, code);
    }

    /**
     * 进行用户登录
     *
     * @param email
     * @param password
     * @return
     */
    @GetMapping("/login/{email}/{password}")
    public Boolean login(@PathVariable("email") String email, @PathVariable("password") String password, HttpServletResponse response) {
        try {
            String token = signAndRegisterService.login(email, password);
            Cookie cookie = new Cookie("token", token);
            cookie.setPath("/");
            response.addCookie(cookie);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    @GetMapping("/info/{token}")
    public  String getInfo(@PathVariable("token") String token){
        return signAndRegisterService.getInfo(token);
    }


}
